import functools
import json
import random

import config


def returns_json(handler):

  @functools.wraps(handler)
  def SerializeResult(self):
    json.dump(handler(self), self.response.out)

  return SerializeResult


def chaos_monkey(handler):

  @functools.wraps(handler)
  def IntroduceFailures(self):
    if random.random() < config.CHAOS_PROBABILITY:
      self.response.headers['Retry-After'] = '0'
      self.error(503)
      return
    return handler(self)

  return IntroduceFailures


def weak_security_checks(handler):

  @functools.wraps(handler)
  def CheckOriginHeader(self):
    origin = self.request.headers.get('Origin')
    if origin:
      host = self.request.headers.get('Host')
      possible_origins = {
        'http://%s' % host,
        'https://%s' % host,
      }
      if origin not in possible_origins:
        self.error(403)
        self.response.out.write('Origin/Host header mismatch')
        return
    return handler(self)

  return CheckOriginHeader

